import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getSensorData, getSensorDataPaged, getLatestSensorData, getHourlyAverageData, getHourlyData, getDailyStatistics, getSensorDataByRange, getRecentDaysData, getLatest10Data, getMonthlyStatistics, getAutoAggregatedData, testDatabase } from '@/api/sensor'

export const useSensorStore = defineStore('sensor', () => {
  // 状态
  const latestData = ref(null)
  const historyData = ref([])
  const hourlyData = ref([])
  const dailyData = ref([])
  const monthlyData = ref([])
  const autoAggregatedData = ref([])
  const aggregationType = ref('raw') // 'raw', 'hourly', 'daily', 'monthly'
  const recentData = ref([])
  const loading = ref(false)
  const error = ref(null)

  // 统计信息
  const statistics = ref({
    totalCount: 0,
    todayCount: 0,
    last24HoursCount: 0
  })

  // 分页状态
  const pagination = ref({
    page: 0,
    size: 100,
    totalPages: 0,
    totalItems: 0
  })

  // 数据库测试结果
  const dbTestResult = ref(null)

  // 计算属性
  const hasData = computed(() => {
    return latestData.value !== null
  })

  const historicalData = computed(() => {
    return historyData.value
  })

  const temperatureRange = computed(() => {
    if (!historyData.value.length) return { min: 0, max: 0 }
    const temps = historyData.value.map(item => parseFloat(item.temperature)).filter(t => !isNaN(t))
    return {
      min: Math.min(...temps),
      max: Math.max(...temps)
    }
  })
  const humidityRange = computed(() => {
    if (!historyData.value.length) return { min: 0, max: 0 }
    const humidities = historyData.value.map(item => parseFloat(item.humidity)).filter(h => !isNaN(h))
    return {
      min: Math.min(...humidities),
      max: Math.max(...humidities)
    }
  })
  const averageValues = computed(() => {
    if (!historyData.value.length) {
      return {
        temperature: 0,
        humidity: 0,
        pressure: 0,
        lightIntensity: 0
      }
    }

    const validData = historyData.value.filter(item =>
      item.temperature && item.humidity && item.pressure && item.lightIntensity
    )

    if (!validData.length) {
      return {
        temperature: 0,
        humidity: 0,
        pressure: 0,
        lightIntensity: 0
      }
    }
    const sum = validData.reduce((acc, item) => {
      acc.temperature += parseFloat(item.temperature)
      acc.humidity += parseFloat(item.humidity)
      acc.pressure += parseFloat(item.pressure)
      acc.lightIntensity += parseInt(item.lightIntensity)
      return acc
    }, { temperature: 0, humidity: 0, pressure: 0, lightIntensity: 0 })
    return {
      temperature: (sum.temperature / validData.length).toFixed(2),
      humidity: (sum.humidity / validData.length).toFixed(2),
      pressure: (sum.pressure / validData.length).toFixed(2),
      lightIntensity: Math.round(sum.lightIntensity / validData.length)
    }
  })
  // 动作
  const fetchLatestData = async () => {
    try {
      loading.value = true
      error.value = null
      const response = await getLatestSensorData()
      if (response.success) {
        latestData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取最新数据失败'
      console.error('获取最新数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchHistoricalData = async (hours = 24) => {
    try {
      loading.value = true
      error.value = null
      console.log(`开始获取历史数据，小时数: ${hours}`)

      // 对于大数据量查询（超过7天的数据），使用分页API
      if (hours > 168) { // 7天 = 168小时
        console.log(`数据量较大，使用分页API，小时数: ${hours}`)
        const response = await getSensorDataPaged(hours, 0, 1000) // 获取前1000条数据

        if (response.success) {
          historyData.value = response.data || []
          pagination.value = {
            page: response.page || 0,
            size: response.size || 100,
            totalPages: response.totalPages || 1,
            totalItems: response.totalCount || 0
          }
          console.log(`历史数据获取成功，当前页数据: ${historyData.value.length} 条，总数据: ${pagination.value.totalItems} 条`)
        } else {
          error.value = response.message || '获取历史数据失败'
          console.error('获取历史数据失败:', response.message)
          historyData.value = []
        }
      } else {
        // 对于小数据量查询，使用原来的API
        const response = await getSensorData(hours)
        console.log('历史数据API响应:', response)

        if (response.success) {
          historyData.value = response.data || []
          console.log(`历史数据获取成功，共 ${historyData.value.length} 条记录`)
        } else {
          error.value = response.message || '获取历史数据失败'
          console.error('获取历史数据失败:', response.message)
          historyData.value = []
        }
      }
    } catch (err) {
      error.value = err.message || '获取历史数据失败'
      console.error('获取历史数据失败:', err)
      historyData.value = []
    } finally {
      loading.value = false
    }
  }

  const fetchHourlyAverageData = async (hours = 24) => {
    try {
      loading.value = true
      error.value = null
      const response = await getHourlyAverageData(hours)
      if (response.success) {
        hourlyData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取小时数据失败'
      console.error('获取小时数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchDailyStatistics = async (days = 7) => {
    try {
      loading.value = true
      error.value = null
      const response = await getDailyStatistics(days)
      if (response.success) {
        dailyData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取日统计数据失败'
      console.error('获取日统计数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchDataByTimeRange = async (startTime, endTime) => {
    try {
      loading.value = true
      error.value = null
      const response = await getSensorDataByRange(startTime, endTime)
      if (response.success) {
        historyData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取时间范围数据失败'
      console.error('获取时间范围数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchRecentDaysData = async (days = 7) => {
    try {
      loading.value = true
      error.value = null
      const response = await getRecentDaysData(days)
      if (response.success) {
        historyData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取最近天数数据失败'
      console.error('获取最近天数数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchRecentData = async (limit = 10) => {
    try {
      loading.value = true
      error.value = null
      const response = await getLatest10Data()
      if (response.success) {
        recentData.value = response.data
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取最近数据失败'
      console.error('获取最近数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  const updateStatistics = (stats) => {
    statistics.value = { ...statistics.value, ...stats }
  }

  const clearError = () => {
    error.value = null
  }

  const resetStore = () => {
    latestData.value = null
    historyData.value = []
    hourlyData.value = []
    dailyData.value = []
    monthlyData.value = []
    autoAggregatedData.value = []
    aggregationType.value = 'raw'
    recentData.value = []
    loading.value = false
    error.value = null
    statistics.value = {
      totalCount: 0,
      todayCount: 0,
      last24HoursCount: 0
    }
  }

  const startRealTimeUpdate = (interval = 3000) => {
    const timer = setInterval(() => {
      fetchLatestData()
    }, interval)

    return () => clearInterval(timer)
  }

  // 加载更多分页数据
  const loadMoreHistoricalData = async (hours = 24) => {
    if (pagination.value.page >= pagination.value.totalPages - 1) {
      console.log('已加载全部数据')
      return
    }

    try {
      loading.value = true
      error.value = null
      const nextPage = pagination.value.page + 1
      console.log(`加载更多数据，页码: ${nextPage}，小时数: ${hours}`)

      const response = await getSensorDataPaged(hours, nextPage, pagination.value.size)

      if (response.success) {
        const newData = response.data || []
        historyData.value = [...historyData.value, ...newData]
        pagination.value = {
          page: nextPage,
          size: pagination.value.size,
          totalPages: response.totalPages || pagination.value.totalPages,
          totalItems: response.totalCount || pagination.value.totalItems
        }
        console.log(`加载更多数据成功，当前数据总数: ${historyData.value.length} 条`)
      } else {
        error.value = response.message || '加载更多数据失败'
        console.error('加载更多数据失败:', response.message)
      }
    } catch (err) {
      error.value = err.message || '加载更多数据失败'
      console.error('加载更多数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取月度统计数据
  const fetchMonthlyStatistics = async (months = 12) => {
    try {
      loading.value = true
      error.value = null
      const response = await getMonthlyStatistics(months)
      if (response.success) {
        monthlyData.value = response.data
        historyData.value = response.data // 同时更新historyData以便于图表展示
        aggregationType.value = 'monthly'
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取月度统计数据失败'
      console.error('获取月度统计数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取小时数据（一天内的数据）
  const fetchHourlyData = async (hours = 24) => {
    try {
      loading.value = true
      error.value = null
      const response = await getHourlyData(hours)
      if (response.success) {
        hourlyData.value = response.data
        historyData.value = response.data // 同时更新historyData以便于图表展示
        aggregationType.value = 'hourly'
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取小时数据失败'
      console.error('获取小时数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取月平均数据（一年内的数据）
  const fetchMonthlyAverageData = async (days = 365) => {
    try {
      loading.value = true
      error.value = null
      const response = await getMonthlyStatistics(Math.ceil(days / 30))
      if (response.success) {
        monthlyData.value = response.data
        historyData.value = response.data // 同时更新historyData以便于图表展示
        aggregationType.value = 'monthly'
      } else {
        error.value = response.message
      }
    } catch (err) {
      error.value = err.message || '获取月平均数据失败'
      console.error('获取月平均数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取自动聚合数据
  const fetchAutoAggregatedData = async (hours = 24) => {
    try {
      loading.value = true
      error.value = null
      console.log(`获取自动聚合数据，小时数: ${hours}`)

      const response = await getAutoAggregatedData(hours)
      console.log('自动聚合数据API响应:', response)

      if (response.success && response.data) {
        autoAggregatedData.value = response.data
        historyData.value = response.data // 同时更新historyData以便于图表展示
        aggregationType.value = response.aggregationType

        // 检查数据是否为空
        if (response.data.length === 0) {
          console.warn('自动聚合数据为空')
          error.value = '未找到数据，请尝试其他时间范围'
        } else {
          console.log(`自动聚合数据获取成功，类型: ${response.aggregationType}，数据量: ${response.count}`)
          console.log('数据样本:', response.data[0])
        }
      } else {
        error.value = response.message || '获取自动聚合数据失败'
        console.error('获取自动聚合数据失败:', response.message)
        historyData.value = []
      }
    } catch (err) {
      error.value = err.message || '获取自动聚合数据失败'
      console.error('获取自动聚合数据失败:', err)
      historyData.value = []
    } finally {
      loading.value = false
    }
  }

  // 测试数据库连接和数据
  const testDatabaseConnection = async () => {
    try {
      loading.value = true
      error.value = null
      console.log('开始测试数据库连接')

      const response = await testDatabase()
      console.log('数据库测试响应:', response)

      if (response.success) {
        dbTestResult.value = response.data
        console.log('数据库测试成功:', dbTestResult.value)
        return response.data
      } else {
        error.value = response.message || '数据库测试失败'
        console.error('数据库测试失败:', response.message)
        return null
      }
    } catch (err) {
      error.value = err.message || '数据库测试失败'
      console.error('数据库测试失败:', err)
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    latestData,
    historyData,
    hourlyData,
    dailyData,
    monthlyData,
    autoAggregatedData,
    aggregationType,
    recentData,
    loading,
    error,
    statistics,
    pagination,
    dbTestResult,

    // 计算属性
    hasData,
    historicalData,
    temperatureRange,
    humidityRange,
    averageValues,

    // 动作
    fetchLatestData,
    fetchHistoricalData,
    fetchHourlyAverageData,
    fetchDailyStatistics,
    fetchMonthlyStatistics,
    fetchMonthlyAverageData,
    fetchHourlyData,
    fetchAutoAggregatedData,
    fetchDataByTimeRange,
    fetchRecentDaysData,
    fetchRecentData,
    updateStatistics,
    clearError,
    resetStore,
    startRealTimeUpdate,
    loadMoreHistoricalData,
    testDatabaseConnection
  }
})